<?php

class Mithos_News_Comment {

    private $_id;
    private $_author;
    private $_body;
    private $_created;
    private $_status;
    private $_news;

    public function __construct($id = null) {
        if ($id !== null) {
            $this->read($id);
        }
    }

    public function id($id = null) {
        if ($id === null) {
            return $this->_id;
        }
        $this->_id = $id;
        return $this;
    }

    public function author($author = null) {
        if ($author === null) {
            return $this->_author;
        }
        if (!$author instanceof Mithos_Character) {
            $author = new Mithos_Character($author);
        }
        $this->_author = $author;
        return $this;
    }

    public function body($body = null) {
        if ($body === null) {
            return $this->_body;
        }
        $this->_body = $body;
        return $this;
    }

    public function created($created = null) {
        if ($created === null) {
            return $this->_created;
        }
        $this->_created = $created;
        return $this;
    }

    public function status($status = null) {
        if ($status === null) {
            return empty($this->_status) ? false : (bool)$this->_status;
        }
        $this->_status = $status;
        return $this;
    }

    public function news($news = null) {
        if ($news === null) {
            if (!$this->_news instanceof Mithos_News) {
                return new Mithos_News($news);
            }
            return $this->_news;
        }
        $this->_news = $news;
        return $this;
    }

    public function exists() {
        return $this->id() !== null;
    }

    public function read($id) {
        $result = Mithos_Mssql::getInstance()->fetch('SELECT
            id, status, created, body, 
            author, news_id AS news 
            FROM Mithos.dbo.news_comments
            WHERE id = :id[integer]
        ', array('id' => $id));
        if (!empty($result)) {
            foreach ($result as $key => $value) {
                if (method_exists($this, $key)) {
                    $this->{$key}($value);
                }
            }
        }
    }

    public function insert() {
        try {
            $params = array(
                'author' => $this->author()->name(),
                'body' => $this->body(),
                'status' => $this->status() === null ? 1 : $this->status(),
                'news_id' => $this->news()->id()
            );
            Mithos_Mssql::query('INSERT INTO Mithos.dbo.news_comments (body, author, created, news_id, status) VALUES (:body[string], :author[string], GETDATE(), :news_id[integer], :status[integer])', $params);
        } catch (Exception $e) {
            throw new Exception('Could not insert comment: ' . $e->getMessage());
        }
    }
}

?>